import { Inject, Provide } from '@midwayjs/core';
import { BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Repository, In } from 'typeorm';
import { ProductProductEntity } from '../entity/product';
import { DictInfoEntity } from "../../dict/entity/info";
import { CouponInfoEntity } from '../../coupon/entity/info';
import { CouponUserEntity } from '../../coupon/entity/user';

/**
 * 商品信息
 */
@Provide()
export class ProductProductService extends BaseService {
  @InjectEntityModel(ProductProductEntity)
  productProductEntity: Repository<ProductProductEntity>;

  @InjectEntityModel(DictInfoEntity)
  dictInfoEntity: Repository<DictInfoEntity>;

  @InjectEntityModel(CouponInfoEntity)
  couponInfoEntity: Repository<CouponInfoEntity>;

  @InjectEntityModel(CouponUserEntity)
  couponUserEntity: Repository<CouponUserEntity>;

  /**
   * 批量导入商品
   */
  async importProducts(data: any[]) {
    const result = {
      success: 0,
      fail: 0,
      errors: []
    };

    // 获取所有品牌和系列的字典数据
    const brandDicts = await this.dictInfoEntity.find({
      where: { typeId: 24 }
    });
    const seriesDicts = await this.dictInfoEntity.find({
      where: { typeId: 25 } 
    });

    for (const item of data) {
      try {
        // 查找品牌，如果不存在则创建
        let brand = brandDicts.find(b => b.name === item.品牌);
        if (!brand) {
          const newBrand = new DictInfoEntity();
          newBrand.name = item.品牌;
          newBrand.typeId = 24;
          newBrand.createTime = new Date();
          newBrand.updateTime = new Date();
          brand = await this.dictInfoEntity.save(newBrand);
          brandDicts.push(brand);
        }

        // 查找系列，如果不存在则创建
        let series = seriesDicts.find(s => s.name === item.系列);
        if (!series) {
          const newSeries = new DictInfoEntity();
          newSeries.name = item.系列;
          newSeries.typeId = 25;
          newSeries.createTime = new Date();
          newSeries.updateTime = new Date();
          series = await this.dictInfoEntity.save(newSeries);
          seriesDicts.push(series);
        }

        // 检查是否存在相同商品
        const existProduct = await this.productProductEntity.findOne({
          where: {
            brandId: brand.id,
            series: series.id,
            refraction: item.折射率,
            price: Number(item.价格),
          }
        });

        if (existProduct) {
          result.fail++;
          result.errors.push({
            row: item._index + 1,
            message: '该商品已存在',
            data: item
          });
          continue;
        }

        // 创建商品
        const product = new ProductProductEntity();
        product.name = item.折射率 && item.折射率 !== '0' 
          ? `${item.品牌} ${item.系列} ${item.折射率}`
          : `${item.品牌} ${item.系列}`;
        product.brandId = brand.id;
        product.series = series.id;
        product.price = Number(item.价格);
        product.refraction = item.折射率;
        product.createTime = new Date();
        product.updateTime = new Date();

        await this.productProductEntity.save(product);
        result.success++;
      } catch (error) {
        result.fail++;
        result.errors.push({
          row: item._index + 1,
          message: error.message,
          data: item
        });
      }
    }

    return result;
  }


  async getProductTotalMoney(items: { id: number; count: number }[], couponId?: number) {
    // 收集所有商品ID
    const productIds = [...new Set(items.map(item => item.id))];
    
    const products = await this.productProductEntity.find({
      where: { id: In(productIds) }
    });
    console.log('products', products);

    // 收集所有品牌ID和系列ID
    const dictIds = products.reduce((ids, product) => {
      if (product.brandId) ids.push(product.brandId);
      if (product.series) ids.push(product.series);
      return ids;
    }, []);
    
    // 批量查询字典数据
    const dicts = await this.dictInfoEntity.find({
      where: { id: In(dictIds) }
    });

    // 计算每个商品的详细信息，包含数量
    const details = items.map(item => {
      const product = products.find(p => p.id === item.id);
      return {
        id: product.id,
        name: product.name,
        price: Number(product.price),
        count: item.count,
        subtotal: Number(product.price) * item.count,
        brandName: dicts.find(dict => dict.id === product.brandId)?.name || '',
        seriesName: dicts.find(dict => dict.id === product.series)?.name || '',
        modelNumber: product.modelNumber || '',
        trainCount: product.trainCount || 0,
        giftCount: product.giftCount || 0,
      };
    });
    
    // 计算总金额
    let totalMoney = details.reduce((total, item) => total + item.subtotal, 0);

    // 处理优惠券
    let totalDiscountAmount = 0;
    const discounts = [];
    if (couponId) {
      const userCoupon = await this.couponUserEntity.findOne({
        where: { id: couponId }
      });

      console.log('userCoupon', couponId, userCoupon);
      const coupon = await this.couponInfoEntity.findOne({
        where: { id: userCoupon.couponId }
      });
      
      if (coupon) {
        // 根据优惠券类型计算折扣
        let discountAmount = 0;
        switch (coupon.type) {
          case 0: // 固定金额
            discountAmount = Number(coupon.discountAmount);
            break;
          case 1: // 折扣比例
            discountAmount = Math.ceil(totalMoney * (1-(Number(coupon.discountRatio))));
            break;
        }
        
        // 确保折扣金额不超过订单总额
        discountAmount = Math.min(discountAmount, totalMoney);
        totalDiscountAmount += discountAmount;
        // 添加优惠券信息到优惠列表
        discounts.push({
          userCouponId: couponId, 
          couponId: coupon.id,
          type: 'coupon',
          name: coupon.name,
          discountType: coupon.type,
          discountAmount: discountAmount,
          discountRatio: coupon.discountRatio,
          originalAmount: totalMoney,
          finalAmount: totalMoney - discountAmount
        });
      }
    }

    // 计算最终金额
    const finalMoney = totalMoney - totalDiscountAmount;
    
    return {
      detail: details,
      money: totalMoney,
      totalDiscountAmount: totalDiscountAmount,
      discountInfo: discounts // 返回优惠券信息
    };
  }
}
